﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Data;
using YunSpace.Domain.Entity.OrderFlowManage;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Domain.ViewModel.OrderFlowManage;

namespace YunSpace.Application.SystemManage
{
    public class SalasApp
    {
        public List<SalasModel> GetList() {
            List<SalasModel> result = new List<SalasModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select `状态` as orderState,`销售姓名` as saleName,`客户类型` as clientType,`客户名称` as clientName,`客户等级` as clientElevel,
	                        `所在城市` as City,`行政区域` as Areas,`公司地址` as CompanyAddress,`所属行业` as Industory,`直客名称` as zk_Name,
	                        `品牌名称` as brandName,`所属项目组` as projectName,`联系人` as contractName,`所属部门` as DeportName,`所属职位` as positionName,
	                        `性别` as sex,`手机` as mobliePhone,`公司座机` as phone,`Email` as email,`需求来源` as resource,`活动主题` as activityTheme,
	                        `活动类型` as activityType,`所属行业1` as Industory1,`预算金额` as budgetCash,`搭建时间` as buildDate,`活动开始时间` as activityStart,
	                        `活动结束时间` as activityEnd,`活动城市` as activityCity,`场地类型` as siteType,`活动人数` as activityNum,`场地面积` as siteArea,
	                        `层高` as Cgao,`室内/室外` as homeInout,`备注` as remark,`签单时间` as orderTime,`使用场地` as usingSite,`使用场地1` as usingSite1,
	                        `使用空间` as usingSpace,`场地租金(收入)` as siteCashIn,`配套服务(收入)` as assortIn,`场地方金额(支出)` as siteCashOut,`场地返佣(支出)` as siteRebateOut,
	                        `客户返佣(支出)` as clientRebateOut,	`税金(支出)` as rateOut,`利润` as profit,`利润率` as profitPre
	                        from mydata2 as a where length(a.`客户名称`)>0 order by a.`客户名称` desc";
                result = db.FindList<SalasModel>(strSql);                
            }
            return result;
        }

        public void OperationSalas() {

            try
            {
                List<SalasModel> result = GetList();
                for (int i = 0; i < result.Count; i++)
                {
                    if (i == 113) {
                        string ss = "";
                        string hh = ss+"";
                        
                    }
                    SalasModel sales = result[i];
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        //客户信息
                        SiteClientsEntity client = GetClientEntity(sales.clientName);
                        if (client == null)
                        {
                            client = new SiteClientsEntity();
                            client.Create();
                            client.F_ClientName = sales.clientName;
                            client.F_ClientType = sales.clientType;
                            client.F_ClientLevel = sales.clientElevel;
                            client.F_CityId = sales.City;
                            client.F_AreaId = sales.Areas;
                            client.F_Address = sales.CompanyAddress;
                            client.F_IndustryId = sales.Industory;
                            db.Insert<SiteClientsEntity>(client);
                        }
                        // 需求信息
                        SiteClientsProjectByDemandEntity demand = new SiteClientsProjectByDemandEntity();
                        demand.Create();
                        demand.F_Source = sales.resource;
                        demand.F_IndustryId = sales.Industory1;
                        demand.F_ClientId = client.F_Id;
                        demand.F_ActivityTheme = sales.activityTheme;
                        demand.F_ActivityType = sales.activityType;
                        demand.F_DemandCash = sales.budgetCash == "" ? 0 : Convert.ToDecimal(sales.budgetCash);
                        demand.F_BuildDate = sales.buildDate == "" ? Convert.ToDateTime(null) : Convert.ToDateTime(sales.buildDate);
                        demand.F_ActivityStartDate = sales.activityStart == "" ? Convert.ToDateTime(null) : Convert.ToDateTime(sales.activityStart);
                        demand.F_ActivityEndDate = sales.activityEnd == "" ? Convert.ToDateTime(null) : Convert.ToDateTime(sales.activityEnd);
                        demand.F_ActivityCityId = sales.activityCity;
                        demand.F_SiteType = sales.siteType;
                        demand.F_SiteArea = sales.siteArea == "" ? Convert.ToDecimal(null) : Convert.ToDecimal(sales.siteArea);
                        demand.F_Height = sales.Cgao == "" ? Convert.ToDecimal(null) : Convert.ToDecimal(sales.Cgao);
                        demand.F_PersionNumber = sales.activityNum == "" ? Convert.ToInt32(null) : Convert.ToInt32(sales.activityNum);
                        demand.F_InOut = sales.homeInout;
                        demand.F_Note = sales.remark;
                        demand.F_State = 1;
                        demand.F_CreatorUserId = sales.saleName;

                        //订单信息
                        ClientOrderEntity order = new ClientOrderEntity();
                        order.Create();
                        order.F_FlowUserId = sales.saleName;
                        order.F_DemandId = demand.F_Id;
                        order.F_WorkFormId = "lc1001";
                        if (sales.orderState == "0")// 储备订单
                        {
                            order.F_OrderState = 1;
                            order.F_OrderStateProcess = -1;
                            order.F_State = 1;
                        }
                        else if (sales.orderState == "1")
                        {//签约订单
                            order.F_OrderState = 8;
                            order.F_OrderStateProcess = 1;
                            order.F_State = 1;
                        }
                        else if (sales.orderState == "2")// 关闭订单
                        {
                            order.F_OrderState = 1;
                            order.F_OrderStateProcess = -1;
                            order.F_State = 0;
                        }

                        // 服务公司跟直客关联
                        if (sales.clientType == "2")
                        {
                            SiteClientsEntity zk = GetClientEntity(sales.zk_Name);
                            SiteClientsEntity fw = GetClientEntity(sales.clientName);
                            if (zk != null && fw != null)
                            {
                                SiteClientsServiceMappingEntity serviceMapping = GetServiceMapping(zk.F_Id, fw.F_Id);
                                if (serviceMapping == null)
                                {
                                    serviceMapping = new SiteClientsServiceMappingEntity();
                                    serviceMapping.Create();
                                    serviceMapping.F_ClientId = zk.F_Id;
                                    serviceMapping.F_ServiceId = fw.F_Id;
                                    db.Insert<SiteClientsServiceMappingEntity>(serviceMapping);
                                }
                            }
                        }
                        // 品牌
                        //SiteClientsEntity fw1 = GetClientEntity(sales.clientName);
                        SiteClientsBrandsEntity brands = GetBrandEntity(client.F_Id, sales.brandName);
                        if (brands == null && sales.brandName != "")
                        {
                            brands = new SiteClientsBrandsEntity();
                            brands.Create();
                            brands.F_ClientId = client.F_Id;
                            brands.F_BrandName = sales.brandName;
                            db.Insert<SiteClientsBrandsEntity>(brands);
                        }

                        if (brands != null)
                        {
                            SiteClientsBrandsMappingEntity brandsmapping = new SiteClientsBrandsMappingEntity();
                            brandsmapping.Create();
                            brandsmapping.F_BrandId = brands.F_Id;
                            brandsmapping.F_DemandId = demand.F_Id;
                            db.Insert<SiteClientsBrandsMappingEntity>(brandsmapping);
                        }

                        // 项目组
                        SiteClientsAllProjectsEntity projects = GetProjectEntity(client.F_Id, sales.projectName);
                        if (projects == null && sales.projectName != "")
                        {
                            projects = new SiteClientsAllProjectsEntity();
                            projects.Create();
                            projects.F_ClientId = client.F_Id;
                            projects.F_ProjectName = sales.projectName;
                            db.Insert<SiteClientsAllProjectsEntity>(projects);
                        }

                        if (projects != null)
                        {
                            SiteClientsAllProjectsMappingEntity projectMapping = new SiteClientsAllProjectsMappingEntity();
                            projectMapping.Create();
                            projectMapping.F_DemandId = demand.F_Id;
                            projectMapping.F_ProjectId = projects.F_Id;
                            db.Insert<SiteClientsAllProjectsMappingEntity>(projectMapping);
                        }

                        // 联系人
                        SiteClientsProjectByContactEntity contact = GetContactEntity(client.F_Id, sales.contractName);
                        if (contact == null && sales.contractName != "")
                        {
                            try
                            {
                                contact = new SiteClientsProjectByContactEntity();
                                contact.Create();
                                contact.F_ClientId = client.F_Id;
                                contact.F_Contact = sales.contractName;
                                contact.F_DepartmentId = sales.DeportName;
                                contact.F_PositionId = sales.positionName;
                                contact.F_Sex = sales.sex == "" ? Convert.ToInt32(null) : Convert.ToInt32(sales.sex);
                                contact.F_Phone = sales.mobliePhone.Length > 11 ? "" : sales.mobliePhone;
                                contact.F_Telephone = sales.phone;
                                contact.F_Mail = sales.email;
                                db.Insert<SiteClientsProjectByContactEntity>(contact);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception(ex.Message);
                            }

                        }

                        if (contact != null)
                        {
                            SiteClientsContactMappingEntity contactMapping = new SiteClientsContactMappingEntity();
                            contactMapping.Create();
                            contactMapping.F_ContactId = contact.F_Id;
                            contactMapping.F_DemandId = demand.F_Id;
                            db.Insert<SiteClientsContactMappingEntity>(contactMapping);
                        }
                        //订单台账
                        if (sales.orderState == "1")
                        {
                            ClientOrderBookRecordEntity bookrecord = new ClientOrderBookRecordEntity();
                            bookrecord.Create();
                            bookrecord.F_OrderId = order.F_Id;
                            bookrecord.F_SigningDate = sales.orderTime.Length > 0 ? Convert.ToDateTime(sales.orderTime) : Convert.ToDateTime(null);
                            bookrecord.F_SiteIds = sales.usingSite1;
                            bookrecord.F_SiteNames = sales.usingSite;
                            bookrecord.F_SiteRent = sales.siteCashIn.Length > 0 ? Convert.ToDecimal(sales.siteCashIn) : 0;
                            bookrecord.F_MatingRent = sales.assortIn.Length > 0 ? Convert.ToDecimal(sales.assortIn) : 0;
                            bookrecord.F_SiteExpend = sales.siteCashOut.Length > 0 ? Convert.ToDecimal(sales.siteCashOut) : 0;
                            bookrecord.F_SiteRebate = sales.siteRebateOut.Length > 0 ? Convert.ToDecimal(sales.siteRebateOut) : 0;
                            bookrecord.F_ClientRebate = sales.clientRebateOut.Length > 0 ? Convert.ToDecimal(sales.clientRebateOut) : 0;
                            bookrecord.F_TaxRebate = sales.rateOut.Length > 0 ? Convert.ToDecimal(sales.rateOut) : 0;
                            bookrecord.F_Profit = sales.profit.Length > 0 ? Convert.ToDecimal(sales.profit) : 0;
                            bookrecord.F_ProfitMargin = sales.profitPre.Length > 0 ? Convert.ToDecimal(sales.profitPre) : 0;
                            bookrecord.F_State = 1;
                            db.Insert<ClientOrderBookRecordEntity>(bookrecord);
                        }


                        db.Insert<SiteClientsProjectByDemandEntity>(demand);
                        db.Insert<ClientOrderEntity>(order);
                        db.Commit();
                    }
                }
            }
            catch (Exception ex) {
                throw new Exception(ex.Message);
            }
            
                
        }

        public SiteClientsServiceMappingEntity GetServiceMapping(string zk,string fw) {
            SiteClientsServiceMappingEntity serviceMapping = new SiteClientsServiceMappingEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Clients_ServiceMapping a where a.F_ClientId='" + zk + "' and a.F_ServiceId='"+ fw +"'";
                serviceMapping = db.FindList<SiteClientsServiceMappingEntity>(strSql).FirstOrDefault();
            }
            return serviceMapping;
        }

        public SiteClientsEntity GetClientEntity(string clientname) {
            SiteClientsEntity entity = new SiteClientsEntity();
            using (var db = new RepositoryBase()) {
                string strSql = @"select * from Site_Clients a where a.F_ClientName='"+ clientname + "'";
                entity = db.FindList<SiteClientsEntity>(strSql).FirstOrDefault();
            }
            return entity;
        }

        public SiteClientsProjectByContactEntity GetContactEntity(string clientId,string contactname) {
            SiteClientsProjectByContactEntity result = new SiteClientsProjectByContactEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Clients_ProjectByContact  a where a.F_ClientId='" + clientId + "' and a.F_Contact='" + contactname + "'";
                result = db.FindList<SiteClientsProjectByContactEntity>(strSql).FirstOrDefault();
            }
            return result;
        }

        public SiteClientsBrandsEntity GetBrandEntity(string clientId,string brandname) {
            SiteClientsBrandsEntity result = new SiteClientsBrandsEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Clients_Brands  a where a.F_ClientId='" + clientId + "' and a.F_BrandName='" + brandname + "'";
                result = db.FindList<SiteClientsBrandsEntity>(strSql).FirstOrDefault();
            }
            return result;
        }

        public SiteClientsAllProjectsEntity GetProjectEntity(string clientId,string projectname) {
            SiteClientsAllProjectsEntity result = new SiteClientsAllProjectsEntity();
            using (var db = new RepositoryBase()) {
                string strSql = @"select * from Site_Clients_AllProjects  a where a.F_ClientId='"+ clientId + "' and a.F_ProjectName='"+ projectname + "'";
                result = db.FindList<SiteClientsAllProjectsEntity>(strSql).FirstOrDefault();
            }
            return result;
        }

        public bool IsClientName(string clientName) {
            bool isok = true;
            using (var db = new RepositoryBase()) {
                string strSql = @"select * from Site_Clients a where a.F_ClientName='"+ clientName + "'";
                var result= db.FindList<SiteClientsEntity>(strSql);
                if (result.Count > 0) {
                    isok = false;
                }
            }
            return isok;
        }
    }
}
